package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dtos.UserSearchDto;
import com.usian.search.service.UserSearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserSearchServiceImpl implements UserSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public ResponseResult search(UserSearchDto dto) {
        /**
         * 1:校验参数
         * 2：restHighLevelClient 构建查询条件
         *    searchRequest
         *       boolQueryBuild
         *    searchQueryBuild
         *       分页
         * 3：结果封装  List<map>
         */
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<Map> result = new ArrayList<>();

        try {
            SearchRequest searchRequest =new SearchRequest("app_info_article1");

            SearchSourceBuilder searchSourceBuilder =new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder =new BoolQueryBuilder();

            // title 和content 内容   模糊 or  and
            QueryStringQueryBuilder queryStringQueryBuilder= QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);
            boolQueryBuilder.must(queryStringQueryBuilder);

            //区间查询 publishtime 比较
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
            boolQueryBuilder.filter(rangeQueryBuilder);

            //分页  分页 page size  page=（page-1）*size
            searchSourceBuilder.from(dto.getFromIndex());
            searchSourceBuilder.size(dto.getPageSize());

            //排序
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);

            searchRequest.source(searchSourceBuilder);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            SearchHit[] hits = response.getHits().getHits();

            for(SearchHit hit : hits){
                String source = hit.getSourceAsString();
                Map map = JSON.parseObject(source, Map.class);
                result.add(map);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseResult.okResult(result);
    }
}
